__author__ = 'dracher'
import os
from lxml import etree
from send_http_request import sendHTTPRequest
from public_parameters import DT_XPATH, DTREE_PATH

def get_printer_info(ip):
    res = sendHTTPRequest('GET', '/DevMgmt/ProductConfigDyn.xml', host=ip, s_flag=1)
    return __get_fwNo_printerName_serNO(res['content'])

def __get_fwNo_printerName_serNO(aStr):
    tree = etree.fromstring(aStr).getroottree().getroot()
    bor = lambda i : i.text and i.text or list(i.iterchildren())[0].text
    return [bor(c) for c in [b for b in [a for a in tree.iterchildren() if 'ProductInformation' in a.tag][0].iterchildren()
                             if 'Version' in b.tag or 'MakeAndModelFamily' in b.tag or 'SerialNumber' in b.tag]]

def checkDiscoveryTree(dbWriter=None, host=None):
    rs = sendHTTPRequest(method="GET", url="/DevMgmt/DiscoveryTree.xml", host=host)
    root = etree.XML(rs['content'])
    ns = root.nsmap

    for xp in DT_XPATH:
        for i in root.xpath(xp, namespaces=ns):
            print "Checking Discovery Tree --> %s" % i.text
            res = sendHTTPRequest(method="GET", url=i.text, host=host)
            result = (res['httpstatus'] == 200) and "Pass" or "Fail"
            dbWriter.insert_dTree_check(i.text, 'GET', result, res['httpreason'], res['content'], 'https')

    eTree_local_path = os.path.join(DTREE_PATH, get_printer_info(host)[1].replace(" ", "_")+"_Dtree.txt")
    eTree_printer_path = host + "/DevMgmt/DiscoveryTree.xml"

    etree_local = etree.XML(open(eTree_local_path, "r").read())

    dbWriter.insert_dTree_check_2(eTree_local_path, eTree_printer_path,
            (set([i.tag for i in root.iterchildren()]) == set([i.tag for i in etree_local.iterchildren()])) and "Pass" or "Fail",
            (set(root.itertext()) == set(etree_local.itertext())) and "Pass" or "Fail")

if __name__ == "__main__":
    eTree_local_path = os.path.join(DTREE_PATH, get_printer_info("10.100.14.26")[1].replace(" ", "_")+"_Dtree.txt")
    root = etree.XML(open(eTree_local_path).read())
